﻿using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.ControlLib;
using xiaoxiong.KYJControllersLib;
using xiaoxiong.ScadaProModbusRtu.childFrm;
using xiaoxiong.ScadaProModbusRtu.Common;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace xiaoxiong.ScadaProModbusRtu
{
    public partial class FrmMonitor : Form
    {
        private Timer UpdateTimer;
        public FrmMonitor()
        {
            InitializeComponent();

            this.simpleLed_Falut.BackgroundImage = Properties.Resources.Fault;
            this.simpleLed_Stop.BackgroundImage = Properties.Resources.Stop;
            this.simpleLed_Spare.BackgroundImage = Properties.Resources.Spare;

            UpdateTimer = new Timer();
            UpdateTimer.Interval = 200;
            UpdateTimer.Tick += UpdateTimer_Tick;
            UpdateTimer.Start();

            this.FormClosing += (s, e) =>
            {
                UpdateTimer.Stop(); 
            };
        }



        /// <summary>
        /// 控件更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            UpdateCommon(this.panelEnhanced1);

            if (CommonMethods.sysConfig.AutoLock)
            {
                CommonMethods.tickCount++;

                if (CommonMethods.tickCount == CommonMethods.sysConfig.LockPeriod * 60 * 1000 / this.UpdateTimer.Interval)
                {
                    //锁屏
                    LockPerMethod();
                }
            }
        }

        // 声明Windows API函数
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool LockWorkStation();
        /// <summary>
        ///  锁屏方法
        /// </summary>
        private void LockPerMethod()
        {
            try
            {
                bool isSuccess = LockWorkStation();
                if (!isSuccess)
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    string errorMessage = $"锁屏失败，错误码: {errorCode}";

                    // 常见错误码处理
                    switch (errorCode)
                    {
                        case 5:
                            errorMessage += " (权限不足，请以管理员权限运行)";
                            break;
                        case 1326:
                            errorMessage += " (用户名或密码错误)";
                            break;
                        default:
                            errorMessage += " (未知错误)";
                            break;
                    }
                    CommonMethods.AddLog(true, errorMessage);
                }
                else
                {
                    // 锁屏成功时重置计数器
                    CommonMethods.tickCount = 0;
                    CommonMethods.AddLog(false, "锁屏成功");
                }
            }
            catch (Exception ex)
            {
                CommonMethods.AddLog(true, $"锁屏异常: {ex.Message}");
            }
        }
        private void UpdateCommon(Control parentControl)
        {
            if (CommonMethods.plcDevice != null && CommonMethods.plcDevice.IsConnected)
            {
                foreach (Control control in parentControl.Controls)
                {
                    //显示textshow数据
                    if(control is TextShow textShow )
                    {
                        if (textShow.BindVarName.Length > 0 && textShow.BindVarName != null)
                        {
                            float value = 0.0f;
                            if (float.TryParse(CommonMethods.plcDevice[textShow.BindVarName]?.ToString(),out value))
                            {
                                textShow.CurrentValue = value.ToString("f1");
                            }
                        }
                    }
                    //更新冷却泵状态
                    else if(control is Pump pump)
                    {
                        if (pump.BindVarName.Length > 0 && pump.BindVarName != null)
                        {
                            byte value = 0;
                            if (byte.TryParse(CommonMethods.plcDevice[pump.BindVarName]?.ToString(), out value))
                            {
                                pump.PumpState = value;
                            }
                        }
                    }
                    //更新阀门状态
                    else if (control is Tap tap)
                    {
                        if (tap.BindVarName.Length > 0 && tap.BindVarName != null)
                        {
                            int value = 0;
                            if (int.TryParse(CommonMethods.plcDevice[tap.BindVarName]?.ToString(), out value))
                            {
                                tap.TapState = value;
                            }
                        }
                    }
                    else if (control.HasChildren)
                    {
                        UpdateCommon(control);
                    }
                }
            }
        }
        private void pump2_PumpDoubleClick(object sender, EventArgs e)
        {
            if (sender is Pump pump)
            {
                new FrmPumpControll(pump.PumpIndex).ShowDialog();
            }
        }
        private void TapCommon_DoubleClick(object sender, EventArgs e)
        {
            if (sender is Tap tap)
            {
                new FrmTapControll().ShowDialog();
            }
        }
    }
}
